
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var tiJianRouter = require("./routes/tiJian");
var f_indexRouter = require("./routes/f_index");

var reserveation = require("./routes/reserveation_wxq");
var indexhesuan = require('./routes/indexhesuan')
var swaggerInstall = require("./utils/swagger");
var app = express();

// var { expressjwt: jwt } = require("express-jwt");
// var jsonwebtoken = require("jsonwebtoken");
// const key = "miyao";
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

swaggerInstall(app);

app.use(logger("dev"));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

//配置静态目录
app.use(express.static(path.join(__dirname, 'public')));
//路由的配置，拦截/进入indexRouter/usersRouter
// app.use(cors());
app.use('/', indexRouter);
app.use('/', usersRouter);
app.use('/', f_indexRouter)



//token验证
// app.use(
//   jwt({
//     secret: key, //秘钥名称
//     algorithms: ["HS256"], //解析算法
//     //判断秘钥是否快过期，快过期则生成新秘钥
//     credentialsRequired: false,
//     getToken: function fromHeaderOrQuerystring(req) {
//       //判断请求头里是否有token
//       console.log(req.header, 111);
//       if (req.headers.token) {
//         //获取请求头里的token
//         let token = req.headers.token;
//         console.log(token, "jiu");
//         // 解析token，获取里的信息，信息保存在参数dacode里 iat 创建时间戳 ，exp到期时间戳
//         jsonwebtoken.verify(token, key, function (err, dacode) {
//           let time = dacode.exp - new Date().getTime() / 1000;
//           console.log(time);

//           if (time < 30) {
//             token = jsonwebtoken.sign(
//               {
//                 user: dacode.user,
//               },
//               key,
//               {
//                 expiresIn: "6000s",
//               }
//             );
//             req.body.token = token;
//           }
//         });
//         return token;
//       }
//       return null;
//     },
//   }).unless({ path: ["/login"] })
// );

// app.use("/", function (req, res, next) {
//   if (req.path != "/login" && req.body.token != undefined) {
//     res.setHeader("token", req.body.token);
//   }
//   next();
// });


app.use("/", tiJianRouter);
app.use('/', indexhesuan);

app.use(reserveation);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler

app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});


module.exports = app;
